// pages/audioRoom/audioRoom.js
import {audioRoomAPI} from '../../api/audioRoom/index'
import {$await,Throttle} from '../../utils/util'
import runtime from '../../utils/runtime'
import config from '../../config'
const Pic= require('../../config.js')
const {agoraId} = require('../../config.js')
const AgoraMiniappSDK = require('../../utils/Agora_Miniapp_SDK_for_WeChat')
import {getUserInfo} from '../../api/common/index';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isClick:false,
    dissolveNum:'0',
    imgsrc:'',
	  ewm:true,
    applyShow:'0',
    a:'1',
    b:'2',
    c:'3',

    messageBox:[],
    shang:'1',
    typeNumber:'',
    pushPath:'',
    img_url:'https://images.weserv.nl/?url=',
    avatar:Pic.imgUrlAvatar,
    speaking:1,
    //麦序列表上
    optionList:[],
    //麦序列表下
    optionList1:[],
    isMike:true,
    //融云roomId
    roomId:'',
    //声网token	
    AgoraToken:'',
    role:'',
    channel_name:'',
    token:'',
    uid:'',
    //房间信息
    roomList:[],
    hideEwm:true,
    hideFlag: true,//true-隐藏  false-显示
    animationData: {},//

    //标题
    title:'给宠物安乐死 你赞同么？',
    //房间number
    roomNumber:'',
    //公告是否展示
    isTopic:true,
    //是否是主持人
    isHost:'1',
    playUrl:'',
    
    broadcast1:[
      {number:'1111',nickname:'0',avatar:'/images/audioRoom/nothing.png',state:'1',identity:'1',playUrl:''},
      {number:'1111',nickname:'申请上麦',avatar:'/images/audioRoom/nothing1.png',state:'1',identity:'1',playUrl:''}, 
      {number:'1111',nickname:'申请上麦',avatar:'/images/audioRoom/nothing2.png',state:'1',identity:'1',playUrl:''}, 
      {number:'1111',nickname:'申请上麦',avatar:'/images/audioRoom/nothing3.png',state:'1',identity:'1',playUrl:''}, 
      {number:'1111',nickname:'申请上麦',avatar:'/images/audioRoom/nothing4.png',state:'1',identity:'1',playUrl:''}, 
      {number:'1111',nickname:'申请上麦',avatar:'/images/audioRoom/nothing5.png',state:'1',identity:'1',playUrl:''}, 
     
    ],
    //上麦列表
    broadcast:[],
    //听众
    audience:[],
    client:{},
    isclose:'',
    _options:{},
    authSettingVoice:false,
    userInfoShow:false,
    userInfo:{},//用户信息
    spacktime:30,//倒计时时间
    animationData:{},
    animationShop:{},// 商品弹框动画
    shop:false,//弹窗展示
    channel_number:'',//电商传值频率ID
    host_id:'',//电商传值主持人ID
    goodsList:[],
    isHaveGood:'',//是否有商品
    opt:'2',//1的时候不能用户不能自己开麦
    store:'0',//是否有购物袋
    showTop:false,
    fixed:false,
    fiexTop:0,
    isSelfFlag:0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    console.log(options)
    this.timer=null;
    this.timer1 = null;
    	// scene 需要使用 decodeURIComponent 才能获取到生成二维码时传入的 scene
			const scene = decodeURIComponent(options.scene)
    if(options.scene){
      this.setData({
        _options:options,
        roomNumber:scene,
        isclose:options.from1
      })
     
    }else{
      this.setData({
        _options:options,
        roomNumber:options.roomNumber,
        isclose:options.from1
      })
     
    }
    let animation = wx.createAnimation({
      duration: 1000,
      timingFunction: 'ease',
    })
    this.animation = animation
    console.log('from1==='+options.from1)
    let check_rcToken = setInterval(() => {
			console.log('用户信息',wx.getStorageSync('userInfo'))
			if(wx.getStorageSync('userInfo') && wx.getStorageSync('userInfo').rc_token){
				this.roomStatus();
				clearInterval(check_rcToken)
			}else{
        getUserInfo()
      }
		}, 1000);
    // this.joinRoom()
    // 监听系统消息
    wx.event.on('cb_room',(data)=>{
      // 语音聊天室相关消息
      const audioRoomMassage = [
        'voiceRoomApply',//上麦通知
        // 'voiceRoomReserved', // 预约私信
        'voiceRoomUserJoin', // 用户进入房间
        'voiceRoomUserLeave', // 用户离开房间
        'voiceRoomSpeaking', // 上下麦通知
        'voiceRoomDissolveRoom', // 结束话题
        'voiceRoomMikeControl', // 开/闭麦通知
        'voiceRoomMikeRefuse',//拒绝上麦消息
        'voiceRoomSuperDissolve',//超管解散房间
      ]
      data.forEach(item =>{
        if(audioRoomMassage.includes(item.action)){
          this[item.action](item)
          console.log(this[item.action](item))
        }
      })
    })
    wx.getSetting({
      success(res) {
        console.log(res.authSetting)
        wx.authorize({
          scope: 'scope.record',
          success() {
           that.setData({
            'authSettingVoice':true
          })
          },
          fail(){
            wx.showToast({
              title: '授权麦克风失败',
              icon: "none",
              duration: 1000
           })
          }
        })
      }
    })
  },
  onPageScroll:function(e){
    let that = this
    this.setData({
      showTop:e.scrollTop > 800 ? true :false,
      fixed:e.scrollTop > 300 ? true :false
    })
    
  },
  toTop:function(){
    if (wx.pageScrollTo) {
      wx.pageScrollTo({
        scrollTop: 0,  // 滚动到页面的目标位置，单位 px
        duration: 1000 // 滚动动画的时长，单位 ms
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }
  },
  initAgoraChannel: function(channel_name, APPID) {
    return new Promise((resolve, reject) => {
      let client = {}
      client = new AgoraMiniappSDK.Client()
      //subscribe stream events
      this.subscribeEvents(client);
      this.client = client;
      this.setData({
        client:client
      })
      console.log('===='+this.data.role);
      client.setRole(this.data.role);
      client.init(agoraId, () => {
        client.join(APPID, channel_name, wx.getStorageSync('userInfo').user_id, () => {

          console.log('初始化成功')
          this.userList()
          //and get my stream publish url
          if (this.isBroadcaster()) {
            client.publish(url => {
              console.log(`client publish success`);
              resolve(url);
            }, e => {
              console.log(`client publish failed: ${e.code} ${e.reason}`);
              reject(e)
				})
			}
		})
	})
	}).catch(function(error) {
    // 处理前一个回调函数运行时发生的错误
    console.log('发生错误！', error);
  });
	},
  
  reinitAgoraChannel: function(channel_name) {
    return new Promise((resolve, reject) => {
      let client = {}
      client = new AgoraMiniappSDK.Client()
      //subscribe stream events
      this.subscribeEvents(client);
      let uids = this.data.media.map(item => {
        return item.uid;
      });
      // this.client = client;
      this.setData({
        client:client
      })
      console.log('this.role===='+this.data.role)
      client.setRole(this.data.role);
      client.init(agoraId, () => {
        console.log(`client init success`);
        // pass key instead of undefined if certificate is enabled
        console.log(`rejoin with uids: ${JSON.stringify(uids)}`);
        client.rejoin(this.data.token, channel_name, wx.getStorageSync('userInfo').user_id,uids, () => {
          console.log(`client join channel success`);
          if (this.isBroadcaster()) {
            client.publish(url => {
              console.log(`client publish success`);
              resolve(url);
            }, e => {
              console.log(`client publish failed: ${e.code} ${e.reason}`);
              reject(e)
            });
          } else {
            resolve();
          }
        }, e => {
          console.log(`client join channel failed: ${e.code} ${e.reason}`);
          reject(e)
        })
      }, e => {
        console.log(`client init failed: ${e} ${e.code} ${e.reason}`);
        reject(e);
      });
    }).catch(function(error) {
      // 处理前一个回调函数运行时发生的错误
      console.log('发生错误！', error);
    });;
  },
  isBroadcaster: function() {
    return this.data.role === "broadcaster";
  },
  subscribeEvents: function(client) {
    let _this = this;
    /**
     * sometimes the video could be rotated
     * this event will be fired with ratotion
     * angle so that we can rotate the video
     * NOTE video only supportes vertical or horizontal
     * in case of 270 degrees, the video could be
     * up side down
     */
    client.on("video-rotation", (e) => {
      console.log(`video rotated: ${e.rotation} ${e.uid}`)
      setTimeout(() => {
        const player = this.getPlayerComponent(e.uid);
        player && player.rotate(e.rotation);
      }, 1000);
    });
    /**
     * fired when new stream join the channel
     */
    client.on("stream-added", e => {
      let uid = e.uid;
      const ts = new Date().getTime();
      console.log(`stream ${uid} added`);
      /**
       * subscribe to get corresponding url
       */
      client.subscribe(uid, (url, rotation) => {
        console.log(`stream ${uid} subscribed successful`);
        let media = this.data.media || [];
        let matchItem = null;
        for (let i = 0; i < media.length; i++) {
          let item = this.data.media[i];
          if (`${item.uid}` === `${uid}`) {
            //if existing, record this as matchItem and break
            matchItem = item;
            break;
          }
        }

        if (!matchItem) {
          //if not existing, add new media
          _this.addMedia(1, uid, url, {
            key: ts,
            rotation: rotation
          })
        } else {
          // if existing, update property
          // change key property to refresh live-player
          _this.updateMedia(matchItem.uid, {
            url: url,
            key: ts,
          });
        }
      }, e => {
        console.log(`stream subscribed failed ${e} ${e.code} ${e.reason}`);
      });
    });

    /**
     * remove stream when it leaves the channel
     */
    client.on("stream-removed", e => {
      let uid = e.uid;
      console.log(`stream ${uid} removed`);
      // this.setData({
      //   media: media
      // });
      // this.removeMedia(uid);
      // let broadcast = this.data.broadcast || [];
      // broadcast = broadcast.filter(item => {
      //   return `${item.number}` != `${uid}`
      // });
      // let audience = this.data.audience || [];
      // audience = audience.filter(item => {
      //   return `${item.number}` != `${uid}`
      // });
      // this.setData({
      //     broadcast,
      //     audience
      //  })
    });

    /**
     * when bad thing happens - we recommend you to do a 
     * full reconnect when meeting such error
     * it's also recommended to wait for few seconds before
     * reconnect attempt
     */
    client.on("error", err => {
      let errObj = err || {};
      let code = errObj.code || 0;
      let reason = errObj.reason || "";
      console.log(`error: ${code}, reason: ${reason}`);
      let ts = new Date().getTime();
      if (code === 501 || code === 904) {
        wx.redirectTo({ 
          url: '/pages/audioRoom/audioRoom?roomNumber='+this.data.roomNumber+'&from1='+this.data.isclose
        })
        // this.reconnect();
      }
    });

    /**
     * there are cases when server require you to update
     * player url, when receiving such event, update url into
     * corresponding live-player, REMEMBER to update key property
     * so that live-player is properly refreshed
     * NOTE you can ignore such event if it's for pusher or happens before
     * stream-added
     */
    client.on('update-url', e => {
      console.log(`update-url: ${JSON.stringify(e)}`);
      let uid = e.uid;
      let url = e.url;
      let ts = new Date().getTime();
      if (`${uid}` === `${this.data.uid}`) {
        // if it's not pusher url, update
        console.log(`ignore update-url`);
      } else {
        this.updateMedia(uid, {
          url: url,
          key: ts,
        });
      }
    });
    
    // token 过期
    // 开启此监听需要获取 2.4.7 版本 sdk
    // client.on("onTokenPrivilegeDidExpire", () => {
    //   console.log('当前 token 已过期，请更新 token 并重新加入频道')
    // }); 

  },
  /**
   * remove media from view
   */
  removeMedia: function(uid) {
    console.log(`remove media ${uid}`);
    
    let media = this.data.media || [];
       `${item.uid}` !== `${uid}`
    this.setData({
      media: media
    });

    // if (media.length !== this.data.media.length) {
    //   this.refreshMedia(media);
    // } else {
    //   console.log(`media not changed: ${JSON.stringify(media)}`)
    //   return Promise.resolve();
    // }
  },
  //声网结束
    //取消
    mCancel: function () {
      var that = this;
      that.hideModal();
    },
    //获取用户信息
    async getUserInfo(e){
      let data = {
        'number':e.currentTarget.dataset.number
      }
      let [err,res] = await $await(audioRoomAPI.getUserInfo(data));
      if(res){
        this.setData({
          'userInfoShow':true,
          'userInfo':res
        })
        console.log(res)
       
      }else{
        wx.showToast({
            title: res.m,
            icon: "none",
            duration: 1000
        })
      } 
    },
    //获取房间状态
    async roomStatus(){
      let data = {
        'room_number':this.data.roomNumber
      }
      let [err,res] = await $await(audioRoomAPI.roomStatus(data));
      if(res){
        console.log(res)
        if(res.status == '1'){
          this.joinRoom()
        }else if(res.status == '0'){
          wx.showToast({
            title: '房间暂未开启',
            icon: "none",
            duration: 1000
          })
          setTimeout(()=>{
            wx.redirectTo({
              url:'/pages/salon/salon' 
            })  
          },1000)
        }else if(res.status == '2'){
          wx.showToast({
            title: '房间已结束',
            icon: "none",
            duration: 1000
          })
          setTimeout(()=>{
            wx.redirectTo({ 
              url:'/pages/salon/salon' 
            })  
          },1000)
        }else if(res.status == '3'){
          wx.showToast({
            title: '房主暂时离开，请稍后重试',
            icon: "none",
            duration: 1000
          })
          setTimeout(()=>{
            wx.redirectTo({ 
              url:'/pages/salon/salon' 
            })  
          },1000)
        }
      }else{
        wx.showToast({
            title: res.m,
            icon: "none",
            duration: 1000
        })
      } 
    },
    hideCard(){
      this.setData({
        'userInfoShow':false,
      })
    },
    //判断主持人数量是否6个，不够给加上
    hostNumber(hostList){
      if(hostList.length>=6){
        return hostList
      }else{
        for(var i =0;i<6;i++){
          console.log(hostList[i])
          if(hostList[i] !=undefined){

          }else{
            hostList.push({number:'1111',nickname:'申请上麦',avatar:'/images/audioRoom/nothing'+i+'.png',state:'1',identity:'3',playUrl:''},)
          }
        }
      }
    },
    async follow(e){
      let data = {
        'number':e.currentTarget.dataset.number,
        'type':1
      }
      let [err,res] = await $await(audioRoomAPI.follow(data));
      if(res){
        wx.showToast({
          title: '关注成功',
          icon: "none",
          duration: 1000
        })
        this.getUserInfo(e);
      }else{
        wx.showToast({
            title: res.m,
            icon: "none",
            duration: 1000
        })
      } 
    },
    followNo(e){
      wx.showToast({
        title: '请下载APP，在APP内取消关注',
        icon: "none",
        duration: 3000
      })
    },
    // 显示商品列表
  showShop(e){
    const {show} = e.currentTarget.dataset
    if(show){
      this.getShopList()
    }
    this.setData({shop:true})
    this.animation.height('788rpx').step({ duration: 300 })
    this.setData({
      animationShop: this.animation.export()
    })
  },
  // 商品详情
  buy({currentTarget:{dataset:{info}}}){
    const {id} = info
    let ds_token = wx.getStorageSync('userInfo').ds_token
    let oId = wx.getStorageSync('userInfo').openid
    let url = `${config.dsUrl}/detail/${id}?from1=wxapp&isToken=${ds_token}&oId=${oId}`
    wx.navigateTo({
      url: '/pages/webview/webview?webURL=' + encodeURIComponent(url),
    })
  },
  //商品列表
  async getShopList(){
    let data = {
      'number':this.data.host_id,
      'channel_id':this.data.channel_number,
      is_live:'1'
    }
    let [err,res] = await $await(audioRoomAPI.getShopList(data));
    if(res){
      console.log(res)
      if(res.list.length>0){
        this.setData({
          isHaveGood:true
        })
      }else{
        this.setData({
          isHaveGood:false
        })
      }
      this.setData({
        goodsList:res.list
      })
    }else{
      wx.showToast({
          title: res.m,
          icon: "none",
          duration: 1000
      })
    } 
  },
  hideShop(){
    this.animation.height('0rpx').step({ duration: 300 })
    this.setData({
      animationShop: this.animation.export()
    },()=>{
      wx.nextTick(()=>{
        this.setData({shop:false})
      })
    })
  },
  // 分享遮罩
  showEwm(){
    var that = this;
    that.setData({
      hideEwm: false,
    })
    // 创建动画实例
    var animation = wx.createAnimation({
      duration: 400,//动画的持续时间
      timingFunction: 'ease',//动画的效果 默认值是linear->匀速，ease->动画以低速开始，然后加快，在结束前变慢
    })
    this.animation = animation; //将animation变量赋值给当前动画
    var time2 = setTimeout(function () {
      that.slideIn();//调用动画--滑入
      clearTimeout(time2);
      time2 = null;
    }, 100)
  },
   // 隐藏遮罩层
   hideModal1: function () {
    var that = this;
    var animation = wx.createAnimation({
      duration: 400,//动画的持续时间 默认400ms
      timingFunction: 'ease',//动画的效果 默认值是linear
    })
    this.animation = animation
    that.slideDown();//调用动画--滑出
    var time2 = setTimeout(function () {
      that.setData({
        hideEwm: true
      })
      clearTimeout(time2);
      time2 = null;
    }, 220)//先执行下滑动画，再隐藏模块
    
   },
   	    //生成分享的二维码
	async getUnlimited(e){
			this.hideModal1()	
    console.log(e)
    let data = {
      'scene':this.data.roomNumber,
       'page': 'pages/audioRoom/audioRoom',
       'width':'400',
      //  'auto_color': false,
      //  'line_color':[{"r":0,"g":0,"b":0}],
        // 'is_hyaline':true
    }
    
    let [err,res] = await $await(audioRoomAPI.getUnlimited(data));
    if(res){
      console.log(res)
      let url = 'data:image/png;base64,' + res.buffer
      this.setData({
        imgsrc:url,
        ewm:false
      })

    }else{
   wx.showToast({
      title: res.m,
      icon: "none",
      duration: 1000
   })
 } 
},
ewmHide(){
this.setData({
  ewm:true
})
},
saveimg:function(){
var _this=this
this.setData({
  ewm:true
})
//获取文件管理器对象
const fs = wx.getFileSystemManager()

//文件保存路径
const Imgpath = wx.env.USER_DATA_PATH + '/qrcodeImg' + '.png'
//_this.data.imgsrc   base64图片文件
let imageSrc = _this.data.imgsrc.replace(/^data:image\/\w+;base64,/, '')

//写入本地文件
fs.writeFile({
  filePath: Imgpath,
  data: imageSrc,
  encoding: 'base64',
  success (res) {
    console.log(res)
    
    //保存到手机相册
    wx.saveImageToPhotosAlbum({
      filePath: Imgpath,
      success(res) {
        console.log(res)
        wx.showToast({
          title: '保存成功',
          icon: 'success'
        })
      },
      fail:function(err){
        console.log("失败了")
        console.log(err)
      }
    })
    
    
  }
})
},
    // ---modal
    // 显示遮罩层
    showModal: function () {
      var that = this;
      this.speakingList()
      that.setData({
        hideFlag: false,
        applyShow:0
      })
      // 创建动画实例
      var animation = wx.createAnimation({
        duration: 400,//动画的持续时间
        timingFunction: 'ease',//动画的效果 默认值是linear->匀速，ease->动画以低速开始，然后加快，在结束前变慢
      })
      this.animation = animation; //将animation变量赋值给当前动画
      var time1 = setTimeout(function () {
        that.slideIn();//调用动画--滑入
        clearTimeout(time1);
        time1 = null;
      }, 100)
    },
   // 隐藏遮罩层
   hideModal: function () {
    var that = this;
    var animation = wx.createAnimation({
      duration: 400,//动画的持续时间 默认400ms
      timingFunction: 'ease',//动画的效果 默认值是linear
    })
    this.animation = animation
    that.slideDown();//调用动画--滑出
    var time1 = setTimeout(function () {
      that.setData({
        hideFlag: true
      })
      clearTimeout(time1);
      time1 = null;
    }, 220)//先执行下滑动画，再隐藏模块
    
   },
  //动画 -- 滑入
  slideIn: function () {
    this.animation.translateY(0).step() // 在y轴偏移，然后用step()完成一个动画
    this.setData({
      //动画实例的export方法导出动画数据传递给组件的animation属性
      animationData: this.animation.export()
    })
  },
 //动画 -- 滑出
 slideDown: function () {
  this.animation.translateY(300).step()
  this.setData({
    animationData: this.animation.export(),
  })
},

  showTopic:function(e){
    this.setData({
      isTopic:!this.data.isTopic
    })
    if(this.data.isTopic){
      let that = this
      var query = wx.createSelectorQuery();
      //选择id
      query.select('#height').boundingClientRect()
      query.exec(function(res) {
          //res就是 所有标签为mjltest的元素的信息 的数组
          console.log(res);
          //取高度
          console.log(res[0].height);
          that.setData({
            fiexTop: res[0].height*2+80+84
          })
      })
    }else{
      this.setData({
        fiexTop: 80+80
      })
      
    }
},
  //加入房间
  async joinRoom(){
    let that = this;
    let params = {
      room_number:this.data.roomNumber
    }
    let [err,res] = await $await(audioRoomAPI.joinRoom({...params}))
    if(res){
      if(res.c=='484'){
        wx.redirectTo({ 
          url:'/pages/salon/salon' 
        })  
        return; 
      }
      console.log(res.room_id,'进入语音房后拿到的roomid')
      let rongStatus = setInterval(() => {
        if(wx.$rong_success){
          wx.join_room(res.room_id)
          clearInterval(rongStatus)
        }
      }, 500);
      this.setData({
        roomList:res.room,
        isHost:res.broadcast,
        roomId:res.room_id,
        role:res.broadcast == '1'? 'broadcaster':'audience',
        channel_name:res.channel_name,
        token:res.token,
        uid:res.room.uid,
        channel_number:res.room.channel_number,
        host_id:res.room.number,
        store:res.room.store_switch
      })
      setTimeout(()=>{
        var query = wx.createSelectorQuery();
        //选择id
        query.select('#height').boundingClientRect()
        query.exec(function(res) {
            that.setData({
              fiexTop: res[0].height*2+80+80
            })
        },500)
      })
      this.initAgoraChannel(res.channel_name,res.token,res.broadcast,res.room.uid).then(url => {
        console.log(`pushing ${url}`);
        let ts = new Date().getTime();
        if (this.isBroadcaster()) {
          // first time init, add pusher media to view
          this.addMedia(0, res.room.uid, url, {
            key: ts
          });
        }
      }).catch(e => {
        console.log(`init agora client failed: ${e}`);
        wx.showToast({
          title: `客户端初始化失败`,
          icon: 'none',
          duration: 5000
        });
      });
    }else{
      wx.redirectTo({ 
        url:'/pages/salon/salon' 
      })  
    }
  },
  addMedia(mediaType, uid, url, options) {
    console.log(`add media ${mediaType} ${uid} ${url}`);
    let media = this.data.media || [];
    if (mediaType === 0) {
      //pusher
      media.splice(0, 0, {
        key: options.key,
        type: mediaType,
        uid: `${uid}`,
        holding: false,
        url: url,
        left: 0,
        top: 0,
        width: 0,
        height: 0
      });
    } else {
      //player
      media.push({
        key: options.key,
        rotation: options.rotation,
        type: mediaType,
        uid: `${uid}`,
        holding: false,
        url: url,
        left: 0,
        top: 0,
        width: 0,
        height: 0
      });
    }
    this.setData({
      media:media
    })
  },
  updateMedia: function(uid, options) {
    let media = this.data.media || [];
    let changed = false;
    for (let i = 0; i < media.length; i++) {
      let item = media[i];
      if (`${item.uid}` === `${uid}`) {
        media[i] = Object.assign(item, options);
        changed = true;
       
        break;
      }
    }

    if (changed) {
      return  this.setData({
        media: media
      });
    } else {
     
      return Promise.resolve();
    }
  },
    /**
   * reconnect when bad things happens...
   */
  reconnect: function() {
    // wx.showToast({
    //   title: `尝试恢复链接...`,
    //   icon: 'none',
    //   duration: 5000
    // });
    // always destroy client first
    // *important* miniapp supports 2 websockets maximum at same time
    // do remember to destroy old client first before creating new ones
    this.data.client && this.data.client.destroy();
    
    // this.onLoad(this.data._options);
    this.reconnectTimer = setTimeout(() => {
      console.log(this.data.uid);
      console.log(this.data.channel_name);
      let uid = this.data.uid;
      let channel = this.data.channel_name;
      this.reinitAgoraChannel(channel,uid).then(url => {
        let ts = new Date().getTime();

        if (this.isBroadcaster()) {
          if (this.hasMedia(0, this.data.uid)) {
            // pusher already exists in media list
            this.updateMedia(this.uid, {
              url: url,
              key: ts,
            });
          } else {
            // pusher not exists in media list
            console.log(`pusher not yet exists when rejoin...adding`);
            this.addMedia(0, this.data.uid, url, {
              key: ts
            });
          }
        }
      }).catch( async e => {
        console.log(`${e}`);
        console.log('------------------------------------------------------------------');
        wx.event.off('cb_room')
        this.data.client.leave(function (res) {
          console.log('用户离开直播间')
        }, function (err) {
            // 发布失败
            console.log("用户离开直播间失败" + err);
        });
        await wx.exit_room()
        return this.onLoad(options);
      });
    }, 1 * 1000);
  },
  // 进房获取用户列表
  async userList(){
    let params = {
      room_number:this.data.roomNumber
    }
    let [err,res] = await $await(audioRoomAPI.userList({...params}))
    console.log(res)
    if(res){
     
      let broadcast = res.broadcast.map(item =>{
        if(item.opt == '1'){
          item.state = '3';
        }
        return {
          ...item,
        
        }
      })
      this.hostNumber(broadcast)
      let audience = res.audience.map(item =>{
        return {
          ...item,
         
        }
      })
      this.setData({broadcast:broadcast,audience:audience})
      // this.addN()
    }else{
      wx.redirectTo({ 
        url:'/pages/salon/salon' 
      })  
      return; 
    }
  },
  //麦序列表
  async speakingList(){
    let params = {
      room_number:this.data.roomNumber
    }
    let [err,res] = await $await(audioRoomAPI.speakingList({...params}))
    if(res){
      let optionList = res.broadcast.map(item =>{
        return {
          ...item
         
        }
      })
      let optionList1 = res.apply_list.map(item =>{
        return {
          ...item
        
        }
      })
      this.setData({optionList:optionList,optionList1:optionList1})
    }
  },
  //房主下麦主播
  async cannelSpeaking(e) {
    this.setData({
      isClick:true
    })
		let [err, res] = await $await(audioRoomAPI.cannelSpeaking({
		  room_number:this.data.roomNumber,
			user_number: e.currentTarget.dataset.number
		}))
		if (res) {
        this.hideModal()
        this.setData({
          isClick:false
        })
		}else{
      wx.showToast({
        title: '接口报错',
        icon: 'none',
        duration: 2000,
      })
    }
  },
  //自己下麦
  async myselfSpeaking(e) {
    console.log(this.data.isClick)
    if(this.data.isClick){
      return
    }
    this.setData({
      isClick:true
    })
		let [err, res] = await $await(audioRoomAPI.myselfSpeaking({
		  room_number:this.data.roomNumber,
	
		}))
		if (res) {
      setTimeout(() => {
        this.setData({
          isClick:false
        })
      }, 3000)
     
		}else{
      wx.showToast({
        title: '接口报错',
        icon: 'none',
        duration: 2000,
      })
    }
  },
  //取消上麦
  async refuseSpeaking(){
    console.log(this.data.isClick)
    if(this.data.isClick){
      return
    }
    this.setData({
      isClick:true
    })
		let [err, res] = await $await(audioRoomAPI.refuseSpeaking({
      room_number:this.data.roomNumber,
      user_number:wx.getStorageSync('userInfo').user_id
	
		}))
		if (res) {
      this.setData({
        isClick:false,
        shang:2
      })
      this.intervalTimer(30)
     
		}else{
      wx.showToast({
        title: '接口报错',
        icon: 'none',
        duration: 2000,
      })
    }
  },
  //房主同意上麦主播
  async agreeSpeaking(e) {
    let [err, res] = await $await(audioRoomAPI.agreeSpeaking({
      room_number:this.data.roomNumber,
      user_number: e.currentTarget.dataset.number
    }))
    if (res) {
      this.speakingList()
    
    }
  },
  //结束话题
  async dissolve(e) {
    let [err, res] = await $await(audioRoomAPI.dissolve({
      room_number:this.data.roomNumber,
    }))
    if (res) {
      wx.navigateBack({
        delta: 1  // 返回上一级页面。
      }) 
      this.data.client.destroy(function (res) {
            console.log('销毁客户端对象')
        }, function (err) {
          // 发布失败
          console.log("销毁客户端对象失败" + err);
      });
     
    }
  },
  //用户申请上麦
  async speaking(e) {
    if(this.data.authSettingVoice === false){
      wx.showToast({
        title: '请先授权小程序使用麦克风',
        icon: "none",
        duration: 1000
     })
     return;
    }
    let [err, res] = await $await(audioRoomAPI.speaking({
      room_number:this.data.roomNumber,
    }))
    if (res) {
      this.setData({
        shang: 0
      })
     
      wx.showToast({
        title: res.message,
        icon: 'none',
        duration: 2000,
      })
    }
  
  },
   //关麦
   async closeMike(e) {
     console.log(e)
     if(e.currentTarget.dataset.number != undefined){
       if(e.currentTarget.dataset.number != wx.getStorageSync('userInfo').user_id){
         return;
       }
     }
    let [err, res] = await $await(audioRoomAPI.closeMike({
      room_number:this.data.roomNumber,
      opt:2,
    }))
    if (res) {
      this.setData({
        isMike: !this.data.isMike
      })
    }
  },
  //上麦通知消息
  voiceRoomApply(e){
    this.setData({
      applyShow:1
     
    });
  },
  //用户进房消息
  voiceRoomUserJoin(e){
    console.log(e,'eeee')
    var _this = this
    if(e.content.is_master==1){
      for (let i = 0; i < _this.data.broadcast.length; i++) {
        if (e.content.user_info.number==_this.data.broadcast[i].number) {
          var isYes=1
        }
        if(isYes!=1){
          console.log(_this.data.broadcast)
            _this.setData({
              broadcast:e.content.user_info.concat(_this.data.broadcast)
            })
        }
      }
    }else{
      // console.log('用户进房')
      if(wx.getStorageSync('userInfo').user_id==(e.content.number)){

      }else{

     
      for (let i = 0; i < _this.data.audience.length; i++) {
        if (e.content.user_info.number==_this.data.audience[i].number) {
         var isYes1=1
        }
       
      }
      if(isYes1!=1){
        // console.log('222')
        // console.log( _this.data.audience)
        this.setData({
          audience: this.data.audience.concat(e.content.user_info),
          
        });
        
      }
    }
      // console.log('用户进房结束')
    }
  },
   //用户离开消息
   voiceRoomUserLeave(e){
     console.log(e,'离开')
     var that = this;
    // if(this.timer) {
    //   return clearTimeout(this.timer)
    // }
    // this.timer = setTimeout(() => {
    console.log(e,'用户离开消息')
    var _this = this
    let user_info =e.content
    if(e.content.user_type==1){
      if(e.content.is_master==1){
        if(e.content.type==1){
          wx.showToast({
            title: '房主暂离，正在快马加鞭赶回来',
            icon: 'none',
            duration: 2000,
          })
        }else{
          wx.showModal({
            content: '主持人已离开房间',
            showCancel:false,
            confirmText:'逛逛其他',
            confirmColor:'#FF3C39',
            success (res) {
              if (res.confirm) {
                console.log('用户点击确定')
                
                wx.redirectTo({
                  url:'/pages/salon/salon'
                }) 
              }
            }
          })
        }
      }else{
       if(wx.getStorageSync('userInfo').user_id==(e.content.number)){
        that.data.client.muteLocal('audio', () => {
          console.log('muteLocal success')
        }, err => {
          console.log(err)
        });
        that.client.unpublish(() => {
        }, e => {
        });
        that.data.client.leave(function (res) {
          console.log('主播离开直播间')
        }, function (err) {
          // 发布失败
          console.log("主播离开直播间失败" + err);
      });
       }
      }
   
    }else{
    
    }
    let broadcast = this.data.broadcast.filter(item => item.number != user_info.number)
    this.hostNumber(broadcast)
    let audience = this.data.audience.filter(item => item.number != user_info.number)
      this.setData({
        broadcast,
        audience
      })
  },
  //上下麦通知
  voiceRoomSpeaking(e){
    console.log(e.content,'上下麦通知')
    var _this = this
    let user_info =e.content.user_info
    let is_self = wx.getStorageSync('userInfo').user_id==e.content.user_info.number
    if(is_self){
      if(e.content.type == 1){
        this.setData({
          speaking:0
        })
        wx.showToast({
          title: `您已上麦`,
          icon: 'none',
          duration: 2000
        });
      }else{
        this.setData({
          role:'audience',
          speaking:1,
          shang:1,
          isMike:true
        })
        this.data.client.setRole('audience')
        this.data.media=[]
        this.client.unmuteLocal('audio', () => {
          console.log('unmuteLocal success')
        }, err => {
          console.log(err)
        });
        this.data.client && this.data.client.unpublish();
        this.data.client.destroy(function (res) {
            console.log('销毁客户端对象')
        }, function (err) {
          // 发布失败
          console.log("销毁客户端对象失败" + err);
        });
        this.initAgoraChannel(this.data.channel_name,this.data.token,this.data.role,this.data.uid).then(url => {
          console.log(`pushing ${url}`);
          let ts = new Date().getTime();
          if (this.isBroadcaster()) {
            // first time init, add pusher media to view
            this.addMedia(0, this.data.uid, url, {
              key: ts
            });
          }
        }).catch(e => {
          console.log(`init agora client failed: ${e}`);
          wx.showToast({
            title: `客户端初始化失败`,
            icon: 'none',
            duration: 5000
          });
        });
      }
    }
    if(e.content.type=='1'){
      let audience = this.data.audience.filter(item => item.number != user_info.number)
      let broadcast = e.content.broadcast.map(item =>{
        if(item.number != wx.getStorageSync('userInfo').user_id){
          return {
            ...item,
            state:item.opt == '1'?'3':item.mike_open,
            identity:item.is_master
          }
        }
        else{
          return {
            ...item,
            state:item.opt == '1'?'4':item.mike_open,
            identity:item.is_master
          }
        }
      })
      console.log(broadcast);
      this.hostNumber(broadcast)
      this.setData({
        broadcast,
        audience
      })
      if(e.content.user_info.number == wx.getStorageSync('userInfo').user_id && this.data.role != 'broadcaster'){
        this.setData({
          role:'broadcaster',
        })
        this.data.client.setRole('broadcaster')
        
        this.data.client.publish(url => {
            let ts = new Date().getTime();
            if (this.isBroadcaster()) {
              this.addMedia(0, this.data.uid, url, {
                key: ts
              });
            }
          }, e => {
            console.log(`client publish failed: ${e.code} ${e.reason}`);
          })
         
      }
      
    }else{
     let broadcast = e.content.broadcast.map(item =>{
      if(item.number !=  wx.getStorageSync('userInfo').user_id){
        return {
          ...item,
          state:item.opt == '1'?'3':item.mike_open,
          identity:item.is_master
        }
      }
      else{
        return {
          ...item,
          state:item.opt == '1'?'4':item.mike_open,
          identity:item.is_master
        }
      }
    })
    console.log(broadcast)
    this.hostNumber(broadcast)
      const number = `number`;
      let audience =  this.data.audience.concat(user_info).reduce((all, next) => all.some((atom) => atom[number] == next[number]) ? all : [...all, next],[]);
      this.setData({
        broadcast,
        audience
      })
    }
  },
   
	//结束话题
  voiceRoomDissolveRoom(e){
    var that =this;
      console.log(e)
      this.data.dissolveNum++
      if(this.data.dissolveNum=='1'){
      if(this.data.isHost!=1){
        wx.showModal({
          content: '主持人已结束话题',
          showCancel:false,
          confirmText:'返回广场',
          confirmColor:'#FF3C39',
          success (res) {
            if (res.confirm) {
              console.log('用户点击确定')
              wx.redirectTo({ 
                url:'/pages/salon/salon' 
              })  
          
             
            }
          }
        })
      }
    }
  },
  //超管结束房间
  voiceRoomSuperDissolve(e){
    var that =this;
      console.log(e)
      this.data.dissolveNum++
      if(this.data.dissolveNum=='1'){
      if(this.data.isHost!=1){
        if(e.content.message ==''){
          wx.redirectTo({ 
            url:'/pages/salon/salon' 
          })  
        }else{
          wx.showToast({
            title: e.content.message,
            icon: 'none',
            duration: 5000
          });
          setTimeout(()=>{
            wx.redirectTo({
              url:'/pages/salon/salon' 
            })  
          },5000)
        }
        
        // wx.showModal({
        //   content: e.content.message,
        //   showCancel:false,
        //   confirmText:'返回广场',
        //   confirmColor:'#FF3C39',
        //   success (res) {
        //     if (res.confirm) {
        //       console.log('用户点击确定')
        //       wx.redirectTo({ 
        //         url:'/pages/salon/salon' 
        //       })  
          
             
        //     }
        //   }
        // })
      }
    }
  },
  //Interval
  intervalTimer(i){
    let timer = setInterval(()=>{
      i--;
      this.setData({
        spacktime:i
      })
      if(i<1){
        this.setData({
          shang:1,
          spacktime:30
        })
        clearInterval(timer);
      }
    },1000)
  },
  //拒绝上麦消息
  voiceRoomMikeRefuse(e){
    console.log(e)
    let is_self = wx.getStorageSync('userInfo').user_id==e.content.number
    if(is_self){
      wx.showToast({
        title: '主持人拒绝了你的上麦申请',
        icon: "none",
        duration: 1000
     })
      this.setData({
        shang:2
      });
      this.intervalTimer(30)
    }
  },
     //开关麦消息
  voiceRoomMikeControl(e) {
    console.log(e)
    var _this = this
    for (let i = 0; i < _this.data.broadcast.length; i++) {
      if (e.content.number==_this.data.broadcast[i].number && e.content.type=='2') {
        if(e.content.opt == '2'){
          _this.setData({
            ['broadcast['+i+'].state']:e.content.type
          })
        }else if(e.content.opt == '1'){
          if(wx.getStorageSync('userInfo').user_id==e.content.number){
            _this.setData({
              ['broadcast['+i+'].state']:4
            })
          }else{
            _this.setData({
              ['broadcast['+i+'].state']:3
            })
          }
          
        }
      }if (e.content.number==_this.data.broadcast[i].number && e.content.type=='1') {
        if(e.content.opt == '2'){
          _this.setData({
            ['broadcast['+i+'].state']:e.content.type
          })
        }else if(e.content.opt == '1'){
          _this.setData({
            ['broadcast['+i+'].state']:e.content.type
          })
        }
      }
    }
    let is_self = wx.getStorageSync('userInfo').user_id==e.content.number
    if(is_self){
      
    if(e.content.type=='1'){
      this.client.unmuteLocal('audio', () => {
        console.log('unmuteLocal success')
      }, err => {
        console.log(err)
      });
      this.setData({
        isMike:true
      })
      // this.client.publish(url => {
      //  console.log(url)
      // }, e => {
       
      // });
       
      } else {
        this.client.muteLocal('audio', () => {
          console.log('muteLocal success')
        }, err => {
          console.log(err)
        });
        // this.client.unpublish(() => {
        this.setData({
          isMike:false,
          opt:e.content.opt
        })
        
        // }, e => {
         
        
        // });
      }
    }else{
      // if(e.content.type=='1'){

      // }else{
      //   this.setData({
      //     opt:e.content.opt
      //   })
      // }
    }
    },
   //开麦
   async openMike(e) {
     if(this.data.opt == '1'){
      wx.showToast({
        title: `你已被主持人禁麦`,
        icon: 'none',
        duration: 2000
      });
      return;
     }
     if(e.currentTarget.dataset.number != undefined){
      if(e.currentTarget.dataset.number != wx.getStorageSync('userInfo').user_id){
        return;
      }
    }
    let [err, res] = await $await(audioRoomAPI.openMike({
      room_number:this.data.roomNumber,
      opt:2,
    }))
    if (res) {
      this.setData({
        isMike: !this.data.isMike
      })
    }
  },
  //跳转到房间管理
  goRoomManage(e){
    	//跳转定位页
			wx.navigateTo({
				url:"/pages/roomManage/roomManage?roomNumber="+this.data.roomNumber+'&isShow=1',
			})
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.popup = this.selectComponent("#popup");
  //   wx.setNavigationBarTitle({
  //     title:this.data.roomList.topic
  // })

  },
  showPopup() {
    this.popup.showPopup();
  },
 
  //取消事件
  _error() {
    console.log('你点击了取消');
    this.popup.hidePopup();
  },
  //确认事件
  _success() {
    console.log('你点击了确定');
    this.popup.hidePopup();
    this.dissolve();


  },
  //用户退出房间
  aaa(){
    var that =this;
    wx.showModal({
      content: '是否退出房间',
      showCancel:true,
      cancelText:'取消',
      cancelColor:'#7f7f7f',
      confirmText:'退出房间',
      confirmColor:'#FF3C39',
      success (res) {
        if (res.confirm) {
          console.log('用户点击确定')
          // that.dissolve();
		  
          wx.navigateBack({  
            delta: 1  // 返回上一级页面。
          }) 
          that.client.leave(function (res) {
            console.log(res)
            console.log('用户离开直播间')
        }, function (err) {
          // 发布失败
          console.log("用户离开直播间失败" + err);
      });
         
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
    
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide:function () {
    if(this.data.client){
      this.data.client.leave(function (res) {
        console.log('用户离开直播间')
      }, function (err) {
        // 发布失败
        console.log("用户离开直播间失败" + err);
      }); 
    }
    if (this.isBroadcaster()) {
      try {
        this.data.client && this.data.client.unpublish();
        for (let i = 0; i < this.data.media.length; i++) {
      
          if (this.data.media[i].type==0) {
            console.log(this.data.media)
            this.setData({
              media: this.data.media.splice(i-1,1)
            });
          }
        }
      } catch (e) {
  
      }
    }
 

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: async function () {
    console.log(JSON.stringify(this.data.client))
    if(JSON.stringify(this.data.client) != '{}'){
      this.data.client.leave(function (res) {
        console.log('用户离开直播间')
      }, function (err) {
        // 发布失败
        console.log("用户离开直播间失败" + err);
      }); 
    }
    if (this.isBroadcaster()) {
      try {
        this.data.client && this.data.client.unpublish();
         for (let i = 0; i < this.data.media.length; i++) {
      
        if (this.data.media[i].type==0) {
          console.log(this.data.media)
          this.setData({
            media: this.data.media.splice(i-1,1)
          });
        }
      }
      } catch (e) {
  
      }
    }
    wx.event.off('cb_room')
    await wx.exit_room()
 //    wx.redirectTo({
 //      delta: 1
	// })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    wx.setNavigationBarTitle({
      title:this.data.name
  })

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    if(res.from =='button'){
      console.log(this.data.roomNumber)
    }
    return{
      title:this.data.roomList.topic,
      path: `pages/audioRoom/audioRoom?roomNumber=`+this.data.roomNumber,
    }
  }
})